package com.dmm.search.interceptors;

import com.dmm.search.utils.ThreadLocalUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserInterceptor implements HandlerInterceptor {
    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头信息
        String authorization = request.getHeader("authorization");
        // 存入ThreadLocal中
        if ("".equals(authorization) || authorization == null) {
            // authorization头信息为空，抛出异常，用户未登录
            throw new RuntimeException("用户未登录");
        }
        Long userId = Long.valueOf(authorization);
        ThreadLocalUtils.setUser(userId);
        // 放行
        return true;
    }

    // 后期处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    // 后置拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除TreadLocal中的信息
        ThreadLocalUtils.removeUser();
    }
}
